{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../../img/ods_stickers.jpg\" />\n",
    "    \n",
    "## [mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course \n",
    "### <center> Author: Alexander Nichiporenko, AlexNich\n",
    "    \n",
    "## <center> Tutorial\n",
    "### <center> \"Anomaly Detection: Isolation Forest\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../../img/out_liar.jpg\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In our course we quite a bit touched unsupervised learning tasks (reduction of dimenstion and clustering), and one more important class remained unnoticed - the detection of anomalies.\n",
    "\n",
    "In data science anomaly detection (outlier or novelty detection) is the identification of rare items, events or observations which raise suspicions by differing significantly from the majority of the data. Typically the anomalous items will translate to some kind of problem such as bank fraud, a structural defect, medical problems or errors in a text. Anomalies are also referred to as outliers, novelties, noise, deviations and exceptions. Outliers often reduce the quality of ML algorithms because models tune to them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A bit of theory and the main idea of algorithm."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the proven anomaly detection algorithms is the Isolation Forest. As the name implies - this is an ensemble of trees, which are built independently of each other. But in this case, the principle of building a tree is different from what is used in regression or classification problems - minimizing the splitting criterion at each step.\n",
    "The trees are also binary, but at each node the feature is chosen randomly, the feature values for splitting are also chosen randomly from the range (min, max) that the feature accepts. The tree is built to the maximum possible depth - when there is only one object in each leaf.\n",
    "With this approach, it appears that the anomalies will get to the final leaf much earlier than normal objects. This is the principle of detecting anomalies which Isolation Forest uses, this algorithm \"isolates\" anomalies  by normal objects at early steps.\n",
    "\n",
    "Perhaps it seems not quite obvious, but we can consider the following one-dimensional toy example - such a set of numbers  [1,20,21,25]. Obviously, the outlier in this case is the number 1. If we choose the threshold for the first splitting (1,25), then in the overwhelming majority of cases, the number 1 will immediately “isolate” in the first leaf of the tree. Let's simulate this situation for 1000 random threshold choices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Importing libaries\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Toy example\n",
    "\n",
    "hits = 0\n",
    "K = 1000\n",
    "for k in range(K):\n",
    "    np.random.seed(k + 101)\n",
    "    split = np.random.uniform(1, 25)\n",
    "    if split < 20:\n",
    "        hits += 1\n",
    "\n",
    "print('The portion of cases when the \"1\" goes to the first leaf:', hits / K)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this way, we can measure the anomaly score using the path length of the object, i.e. the number of edges an observation must pass in the tree going from the root to the terminal node. But we have a problem, for sample data $X$= {$x_1,...,x_n$} the maximum possible height of isolation tree grows in the order of $n$, the average path length grows in the order of $log({n})$. Therefore, we cannot compare the anomaly of objects in samples of different sizes, normalization by any of the above values will not help either. So we will use this formula for normalization:\n",
    "\n",
    "## $$c{(n)} = 2H(n-1) - {2 (n-1)\\over n}$$\n",
    "\n",
    "where $H(n-1)$ is $n$-$Harmonic$ number:\n",
    "\n",
    "## $$H(n-1) = \\sum_{k=1}^{n-1} {1\\over k} \\approx \\gamma\\ {(Euler's\\ constant)} + \\ln{(n-1)} \\approx 0.5772156649 + \\ln{(n-1)}$$\n",
    "\n",
    "$c({n})$ gives the average path length of unsuccessful search in Binary Search Tree (BST). We can use it because isolation tree has a equivalent structure to BST and $c({n})$ equals to estimation of average $h({x})$ for external nodes.\n",
    "\n",
    "So final anomaly score is calculated by this formula:\n",
    "\n",
    "##  $$S(x,n) = {2 ^ {E(x)\\over c(n)}}$$\n",
    "where $E(x)$ - average path length in trees of our forest where example $x$ was isolated:\n",
    "\n",
    "##  $$E(x) = {1\\over N}\\sum_{i=1}^{N} {h(x)_i}$$\n",
    "and $N$ - number of trees in the forest.\n",
    "\n",
    "$S(x,n)$ changes from $0$ to $1$. When $S(x,n)$ of example is very close to $1$ it means that it is definitely anomaly, when it much smaller then $0.5$ then this example safe to be regarded as normal instance, and if all examples have $S(x,n) \\approx 0.5$, then the entire data doesn't have any distinct anomaly.\n",
    "\n",
    "When we decide which example is anomaly we can choose portion of examples with high score or make a threshold in $S(x,n)$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Let's grow our IsolationForest!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this part of the tutorial, we will implement our own Isolation Forest and see how it works with outliers and normal objects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import log as ln\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "# Importing libaries ----\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# External Node - leaf with 1 example\n",
    "\n",
    "\n",
    "class ExNode:\n",
    "    def __init__(self, size):\n",
    "        self.size = size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Internal Node\n",
    "\n",
    "\n",
    "class InNode:\n",
    "    def __init__(self, left, right, split_feature, split_threshold):\n",
    "        self.left = left\n",
    "        self.right = right\n",
    "        self.split_feature = split_feature\n",
    "        self.split_threshold = split_threshold"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build one Isolation tree\n",
    "\n",
    "\n",
    "def IsolationTree(X):\n",
    "    if len(X) <= 1:\n",
    "        return ExNode(len(X))\n",
    "    else:\n",
    "        f = np.random.choice(X.columns)\n",
    "        t = np.random.uniform(X[f].min(), X[f].max())\n",
    "        X_l = X[X[f] < t]\n",
    "        X_r = X[X[f] >= t]\n",
    "        return InNode(IsolationTree(X_l), IsolationTree(X_r), f, t)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build forest\n",
    "\n",
    "\n",
    "def MyIsolationForest(X, n_trees):\n",
    "    forest = []\n",
    "    for i in range(n_trees):\n",
    "        forest.append(IsolationTree(X))\n",
    "    return forest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Depth of external node where object was isolated\n",
    "\n",
    "\n",
    "def path_length(x, tree, curr_depth):\n",
    "    if isinstance(tree, ExNode):\n",
    "        return curr_depth\n",
    "    t = tree.split_feature\n",
    "    if x[t] < tree.split_threshold:\n",
    "        return path_length(x, tree.left, curr_depth + 1)\n",
    "    else:\n",
    "        return path_length(x, tree.right, curr_depth + 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Functions which is needed to calculate degree of anomaly: $E(d), H(x), c(n), S(x,n)$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def E(d):\n",
    "    return np.mean(d)\n",
    "\n",
    "\n",
    "def H(x):\n",
    "    return ln(x) + 0.5772156649\n",
    "\n",
    "\n",
    "def c(n):\n",
    "    return 2 * H(n - 1) - 2 * (n - 1) / n if n > 2 else 1 if n == 1 else 0\n",
    "\n",
    "\n",
    "def S(x, n):\n",
    "    return 2 ** (-E(x) / c(n))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Let's find outliers using our forest!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Firstly we will generate 1-d data - normal distribution and find average path length and $S(x,n)$ of normal and anomaly objects depends on number of trees."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generating normal distributed 1d-data\n",
    "random_generator = np.random.RandomState(42)\n",
    "\n",
    "true_mean = 100\n",
    "true_sigma = 10\n",
    "\n",
    "X_all = random_generator.normal(true_mean, true_sigma, size=500)\n",
    "\n",
    "print(\"Normal interval:\", true_mean - 2 * true_sigma, \"-\", true_mean + 2 * true_sigma)\n",
    "\n",
    "X_outliers = pd.DataFrame(\n",
    "    np.hstack(\n",
    "        [\n",
    "            X_all[X_all < true_mean - 2 * true_sigma],\n",
    "            X_all[X_all > true_mean + 2 * true_sigma],\n",
    "        ]\n",
    "    ),\n",
    "    columns=[\"x\"],\n",
    ")\n",
    "X_normal = pd.DataFrame(list(set(X_all).difference(set(X_outliers))), columns=[\"x\"])\n",
    "X_all = pd.DataFrame(X_all, columns=[\"x\"])\n",
    "\n",
    "print(\"Partition of outliers:\", len(X_outliers) / len(X_all))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 5))\n",
    "plt.hist(X_all[\"x\"], bins=10)\n",
    "plt.hist(X_outliers[\"x\"], bins=10)\n",
    "plt.legend([\"X_all\", \"X_outliers\"])\n",
    "plt.ylabel(\"Count\")\n",
    "plt.xlabel(\"X value\")\n",
    "plt.title(\"Distribution of X\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Outlier for test\n",
    "\n",
    "X_outliers.iloc[2, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Normal example for test\n",
    "\n",
    "X_normal.iloc[0, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "\n",
    "anomaly_x = []\n",
    "normal_x = []\n",
    "\n",
    "anomaly_mean_depth = []\n",
    "normal_mean_depth = []\n",
    "\n",
    "anomaly_S = []\n",
    "normal_S = []\n",
    "\n",
    "for n in range(1, 51, 1):\n",
    "    MyIF = MyIsolationForest(X_all, n)\n",
    "    for iTree in MyIF:\n",
    "        anomaly_x.append(path_length(X_outliers.iloc[2, :], iTree, 0))\n",
    "        normal_x.append(path_length(X_normal.iloc[0, :], iTree, 0))\n",
    "    anomaly_mean_depth.append(E(anomaly_x))\n",
    "    normal_mean_depth.append(E(normal_x))\n",
    "    anomaly_S.append(S(anomaly_x, len(X_all)))\n",
    "    normal_S.append(S(normal_x, len(X_all)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 5))\n",
    "plt.plot(range(1, 51, 1), anomaly_mean_depth, c=\"r\")\n",
    "plt.plot(range(1, 51, 1), normal_mean_depth, c=\"g\")\n",
    "plt.title(\"Average path length (n_trees)\")\n",
    "plt.legend([\"anomaly\", \"normal\"])\n",
    "plt.xlabel(\"Number of trees\")\n",
    "plt.ylabel(\"Average path length\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 5))\n",
    "plt.plot(range(1, 51, 1), anomaly_S, c=\"r\")\n",
    "plt.plot(range(1, 51, 1), normal_S, c=\"g\")\n",
    "plt.title(\"S (n_trees)\")\n",
    "plt.legend([\"anomaly\", \"normal\"])\n",
    "plt.xlabel(\"Number of trees\")\n",
    "plt.ylabel(\"S(x,n)\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see anomaly object has obviously less path depth and bigger $S(x,n)$. Also we don't need many trees to detect anomalies, approximately at 15 trees we reach the asymptote.\n",
    "\n",
    "Ok, let's find outliers in 2-d data. We will use IsolationForest with 30 trees to find our otliers and check the quality of detection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generating 2d-data\n",
    "random_generator = np.random.RandomState(42)\n",
    "\n",
    "# Generating normal data\n",
    "X_normal = random_generator.randn(2000, 2) * 0.5\n",
    "X_normal = pd.DataFrame(X_normal, columns=[\"x1\", \"x2\"])\n",
    "X_normal[\"type\"] = \"normal\"\n",
    "\n",
    "# Generating outliers\n",
    "X_outliers_1 = random_generator.uniform(low=-6, high=6, size=(78, 2))\n",
    "X_outliers_2 = random_generator.uniform(low=-6, high=-3, size=(35, 2))\n",
    "\n",
    "X_outliers = np.vstack([X_outliers_1, X_outliers_2])\n",
    "\n",
    "X_outliers = pd.DataFrame(X_outliers, columns=[\"x1\", \"x2\"])\n",
    "X_outliers[\"R\"] = X_outliers[\"R\"] = np.sqrt(\n",
    "    X_outliers[\"x1\"] ** 2 + X_outliers[\"x2\"] ** 2\n",
    ")\n",
    "X_outliers = X_outliers[X_outliers[\"R\"] > 3].drop(columns=[\"R\"])\n",
    "X_outliers[\"type\"] = \"anomaly\"\n",
    "\n",
    "# Full data\n",
    "\n",
    "X_full = pd.concat([X_normal, X_outliers])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(8, 8))\n",
    "plt.scatter(X_outliers[\"x1\"], X_outliers[\"x2\"], c=\"r\")\n",
    "plt.scatter(X_normal[\"x1\"], X_normal[\"x2\"], c=\"g\")\n",
    "plt.xlabel(\"x1\")\n",
    "plt.ylabel(\"x2\")\n",
    "plt.legend([\"outliers\", \"normal\"])\n",
    "plt.title(\"2d distribution\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_normal.shape, X_outliers.shape, X_full.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "MyIF = MyIsolationForest(X_full[[\"x1\", \"x2\"]], 30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_outliers.iloc[0, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_normal.iloc[0, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "\n",
    "aScore = []\n",
    "\n",
    "\n",
    "for i in range(X_full.shape[0]):\n",
    "    depth = []\n",
    "    for iTree in MyIF:\n",
    "        depth.append(path_length(X_full.iloc[i, :], iTree, 0))\n",
    "\n",
    "    aScore.append(S(depth, X_full.shape[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_full[\"aScore\"] = aScore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = X_full[\"aScore\"].quantile(0.95)\n",
    "X_full[\"Outlier\"] = X_full[\"aScore\"].apply(\n",
    "    lambda x: -1 if x >= t else 1\n",
    ")  # -1 for outliers and 1 for normal object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(X_full[\"aScore\"])\n",
    "plt.xlabel(\"Anomaly Score\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 7))\n",
    "plt.scatter(X_full[\"x1\"], X_full[\"x2\"], c=X_full[\"Outlier\"])\n",
    "plt.title(\"Detection outliers using MyIF\")\n",
    "plt.xlabel(\"x1\")\n",
    "plt.ylabel(\"x2\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reader may notice that our forest works long enough. What will happen to the larger dataset? But fortunately, during the experiments, the authors of this algorithm found that not all data should be used to build a single tree from a forest, which leads not only to an increase in the speed of work, but also improves the quality of anomalies detection. This is because subsamples have fewer normal points ‘interfering’ with anomalies, thus, making anomalies easier to isolate. It is shown on the image below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_sample = X_full.sample(256)\n",
    "plt.figure(figsize=(8, 8))\n",
    "plt.scatter(\n",
    "    X_sample[\"x1\"], X_sample[\"x2\"], c=X_sample[\"type\"].map({\"normal\": 1, \"anomaly\": -1})\n",
    ")\n",
    "plt.xlabel(\"x1\")\n",
    "plt.ylabel(\"x2\")\n",
    "plt.title(\"2d distribution of Sample (size=256)\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We won't develop our IsolationForest and will use sklearn's version with these improvements further."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sklearn is our everything!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import IsolationForest\n",
    "\n",
    "from sklearn.ensemble import IsolationForest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### IsolationForest important params:\n",
    "\n",
    "    n_estimators -  The number of base estimators in the ensemble, default=100.\n",
    "    max_sample - The number of samples from data to train each tree in the forest, default \"auto\" = min(256, n_samples)\n",
    "    max_features - The number of features from data to train each tree in the forest, default = 1.0 (all features)\n",
    "    bootstrap - bootstrap, default=False\n",
    "    contamination - The proportion of outliers in the data set, threshold, default = 0.1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will test this implementation of IF on our 2-d dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "isof = IsolationForest(random_state=77, n_jobs=4, contamination=0.05)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "isof.fit(X_full[[\"x1\", \"x2\"]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Very fast! How about the quality?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# predictions\n",
    "y_pred_full = isof.predict(X_full[[\"x1\", \"x2\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_full[\"Outlier_sk\"] = y_pred_full"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 7))\n",
    "plt.scatter(X_full[\"x1\"], X_full[\"x2\"], c=X_full[\"Outlier_sk\"])\n",
    "plt.title(\"Detection outliers using sklearn.IF\")\n",
    "plt.xlabel(\"x1\")\n",
    "plt.ylabel(\"x2\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Image looks grate! Purple points are outliers which IsolationForest found. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# count of detected outliers \"-1\"\n",
    "X_full.iloc[2000:, 4].value_counts()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see our IsolationForest found almost of outliers."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Time to challenge!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It this part of tutorial we will compare IsolationForest with another algorithms. We will use this data set from Kaggle: https://www.kaggle.com/mlg-ulb/creditcardfraud"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neighbors import LocalOutlierFactor\n",
    "from sklearn.svm import OneClassSVM\n",
    "from xgboost import XGBClassifier\n",
    "\n",
    "pd.options.display.max_columns = 500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_csv(\"creditcard.csv\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's look at the data. All features are numeric, so we will not do any data processing and will train models on what we downloaded. To prevent overfitting of supervised models we will devide initial dataset by train and test parts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = data.drop(columns=[\"Class\"])\n",
    "y = data[\"Class\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.3, random_state=17\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Look at portion of fraud transactions\n",
    "y.mean(), y_train.mean(), y_test.mean(), len(y[y == 1]), len(y), len(y_test), len(\n",
    "    y_test[y_test == 1]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Whoah! Fraud transactions is about 0.2% of all transactions!\n",
    "We will use all algorithms \"from the box\" without tuning parameters. We need to find fraud transcations quickly and as much as possible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# supervised\n",
    "rf = RandomForestClassifier(random_state=42, n_jobs=4)\n",
    "lr = LogisticRegression(random_state=42)\n",
    "xg = XGBClassifier(random_state=42, n_jobs=4)\n",
    "# unsupervised\n",
    "IF = IsolationForest(random_state=42, n_jobs=4, contamination=0.01, n_estimators=300)\n",
    "LOF = LocalOutlierFactor(contamination=0.01, n_jobs=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "rf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "lr.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "xg.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "IF.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "LOF.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rf_pred = rf.predict_proba(X_test)[:, 1]\n",
    "lr_pred = lr.predict_proba(X_test)[:, 1]\n",
    "xg_pred = xg.predict_proba(X_test)[:, 1]\n",
    "IF_pred = IF.predict(X_test)\n",
    "LOF_pred = LOF.fit_predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test[\"true\"] = y_test\n",
    "X_test[\"IF_pred\"] = IF_pred\n",
    "X_test[\"LOF_pred\"] = LOF_pred\n",
    "X_test[\"xg_pred\"] = xg_pred\n",
    "X_test[\"rf_pred\"] = rf_pred\n",
    "X_test[\"lr_pred\"] = lr_pred"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's check how many fraud transactions found each algorithm:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test[X_test[\"IF_pred\"] == -1][\"true\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test[X_test[\"LOF_pred\"] == -1][\"true\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test.sort_values(by=\"rf_pred\", ascending=False)[\"true\"].head(855).value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test.sort_values(by=\"lr_pred\", ascending=False)[\"true\"].head(855).value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test.sort_values(by=\"xg_pred\", ascending=False)[\"true\"].head(855).value_counts()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see Isolation Forest solved this problem worse than supervised algorithms, but on the whole it is very good for the random. And compared to the LOF, the result is much better. And in this case we don't need to know what transactions are fraud - make a train dataset with target variable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the conclusion ot the tutorial I want to summarise everything about Isolation Forest. This algorithm has very simple idea of anomaly detection: it isolates anomalies rather than normal observations. Also Isolation Forest converges quickly with a small ensemble size, which enables it to detect anomalies with high efficiency.\n",
    "\n",
    "If you want to learn more about Isolation Forest, I recommend reading the article from the authors of the algorithm:\n",
    "\n",
    "http://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf\n",
    "\n",
    "https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/tkdd11.pdf\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
